package com.itheima.web.controller;

import com.github.pagehelper.PageInfo;
import com.itheima.domain.Syslog;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

@WebServlet("/syslog")
public class SyslogServlet extends BaseServlet {
    /**
     * 分页查询，按访问时间查询
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    private void list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //需要模糊查询的参数
        String visitTime = req.getParameter("visitTime");
        int pageNum = 1;
        int pageSize = 5;
        if (StringUtils.isNotBlank(req.getParameter("pageNum"))) {
            pageNum = Integer.parseInt(req.getParameter("pageNum"));
        }
        if (StringUtils.isNotBlank(req.getParameter("pageSize"))) {
            pageSize = Integer.parseInt(req.getParameter("pageSize"));
        }
        Syslog syslog = new Syslog();
        syslog.setPage(pageNum);
        syslog.setSize(pageSize);
        syslog.setVisitTime(visitTime);
        PageInfo all = syslogService.findAll(syslog);
        req.setAttribute("page", all);
        req.getRequestDispatcher("/WEB-INF/pages/syslog/syslog-list.jsp").forward(req, resp);
    }

    /**
     * 批量删除
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    private void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String idstr = req.getParameter("ids");
        String[] idArr = idstr.split(",");
        syslogService.delete(idArr);
        list(req, resp);
    }

    /**
     * 导出
     * @param req
     * @param resp
     * @throws IOException
     */
    private void downloadReport(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //返回的数据类型为文件xlsx类型
        resp.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = new String("日志文件.xlsx".getBytes(),"iso8859-1");
        resp.addHeader("Content-Disposition","attachment;fileName="+fileName);

        //生成报告的文件，通过流的形式传导前端
        ByteArrayOutputStream os = syslogService.getReport();
        //获取产生响应的流对象
        ServletOutputStream sos = resp.getOutputStream();
        //将数据从原始的字节流对象中提取出来写入到servlet对应的输出流中
        os.writeTo(sos);
        //刷新流
        sos.flush();
        os.close();
    }
}